package com.example.demo.controller;

import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.example.demo.common.JwtTokenUtils;
import com.example.demo.common.StringUtils;
import com.example.demo.constants.pojo.UserInfo;
import com.example.demo.exception.BizException;
import com.example.demo.sao.ICacheSao;
import com.example.demo.service.IUserService;
import com.example.demo.shiro.ShiroSimpleJwtToken;

import lombok.extern.log4j.Log4j2;

@Log4j2
@Controller
public class BaseController {
	
	@Autowired
	private ICacheSao _cacheSao; //= new CacheSaoImpl();
	
	@Autowired
    private	IUserService _userService; // = new UserServiceImpl();
	
	/**
	 * TOKEN ID
	 */
	protected final String TOKEN="jwt_token";
	
	public UserInfo getCurrentUser(HttpServletRequest request) throws BizException {
		String userName="";
		UserInfo userInfo=null;
		try {
			
			String token=request.getHeader(TOKEN);
		
			//如果 token 为空则获取session
			if(StringUtils.IsNullOrEmpty(token)) {
				
				Subject subject=SecurityUtils.getSubject();	
//				UserInfo userInfo= (UserInfo)subject.getPrincipal();
				userName=(String)subject.getPrincipal();
				userInfo=_userService.QueryUserInfoByUserName(userName);
				
			}
			else {	
				
				ShiroSimpleJwtToken tokenEntity= JwtTokenUtils.serializeToken(token);
				
				Date expireTime= tokenEntity.getExpireTime();
				if(new Date().compareTo(expireTime)>0) {
					throw new BizException("登陆已过期，请重新登陆");
				}
				
				Object cacheObject = _cacheSao.Get(tokenEntity.getUserId());
				
				if(cacheObject==null) {
					throw new BizException("登陆已过期，请重新登陆");
				}

				userName=tokenEntity.getUsername();
				userInfo=_userService.QueryUserInfoByUserName(userName);
			}
			
			System.out.println(userInfo);	
		}
		catch (Exception ex) {
			// TODO: handle exception
			log.error("获取登陆人信息失败："+ex.getMessage(),ex);
			throw new BizException("未获取到登陆人信息");
		}
		return userInfo;
	}
	
}
